package cn.cdeden.resource.unified.controller;

import cn.cdeden.common.core.domain.R;
import cn.cdeden.common.core.exception.ServiceException;
import cn.cdeden.common.core.utils.StringUtils;
import cn.cdeden.common.oss.enumd.OssModuleOperate;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.common.web.core.BaseController;
import cn.cdeden.resource.api.domain.*;
import cn.cdeden.resource.domain.vo.SysOssVo;
import cn.cdeden.resource.unified.domain.dto.*;
import cn.cdeden.resource.unified.domain.vo.FilePreviewVo;
import cn.cdeden.resource.unified.enums.EditorEnums;
import cn.cdeden.resource.unified.service.RemoteUploadFileFilter;
import cn.cdeden.resource.unified.service.UnifiedFileService;
import cn.cdeden.system.api.RemoteUserService;
import cn.cdeden.system.api.model.LoginUser;
import com.alibaba.fastjson2.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.net.URL;
import java.util.Scanner;


/**
 * 文件统一的处理模块 文件预览编辑
 *
 * @ProjectName : KnowCore01
 * @Package : cn.cdeden.resource.updateFile.controller
 * @ClassName : UploadFileController
 * @Author : Yu.
 * @Description : //
 * @Date : 2024/12/22 15:36
 * @Version : 1.0
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/oss/file/date")
public class UnifiedFilePreviewEditingController extends BaseController {


    private final UnifiedFileService uploadFileService;

    private final RemoteUploadFileFilter unificationFile;

    @DubboReference
    private final RemoteUserService userService;





    /***********************************************文件预览 编辑 *******************************************/


    /**
     * 获取 文件信息 预览
     *
     * @param info
     * @return cn.cdeden.common.core.utils.page.TableDataInfo
     * @author Yu.
     * @Description //
     * @Date 2024/12/8 14:46
     **/
    @Operation(summary = "获取文件信息")
//    @ApiEncrypt(response = true) //响应加密
    @PostMapping(value = "/getFileDataInfo")
    public R getFileDataInfo(@Validated @RequestBody OnlinePreviewInfoDto info) {
        String type = info.getType();
        ////获取文件信息数据
        RemoteFile dataInfo = unificationFile.getFileDataInfo(info.getModuleId(), LoginHelper.getUserId(), info.getInfo(), OssModuleOperate.Preview_Edit,type); //获取文件的的信息
        FilePreviewVo fileDataInfo = uploadFileService.getFileDataInfo(dataInfo, info);
        return R.ok(fileDataInfo);
    }




    /**
     * 在线编辑（畅写和onlyOffice）,编辑前获取参数
     *
     * @param info
     * @return cn.cdeden.common.core.domain.R
     * @Date 2024/12/13 11:23
     **/
    @PostMapping(value = "/onlineEditor")
    @ResponseBody
//    @RateLimit(permitsPerSecond = 1.0)  // 每秒允许1个请求
    public R onlineEditor(@Validated @RequestBody OnlinePreviewInfoDto info) {
        LoginUser userInfo;
        try {
            userInfo = LoginHelper.getLoginUser(); //用户信息
        } catch (Exception e) {
            if (StringUtils.isBlank(info.getUserId())) {
                return R.fail("用户名不能为空");
            }
            userInfo = userService.getUserInfo(Long.valueOf(info.getUserId()));
        }
        String avatarName = userInfo.getNickname();
        String username = userInfo.getUsername();
        String userId = Long.toString(userInfo.getUserId());
        String id = info.getModuleId();
        String type = info.getType();
        unificationFile.gssUploadService(type);

        RemoteFile fileDataInfo = unificationFile.getFileDataInfo(id, userInfo.getUserId(), info.getInfo(), OssModuleOperate.Edit_Save,type);
        if (ObjectUtils.isEmpty(fileDataInfo)) {
            throw new RuntimeException("请求参数请求");
        }
        OfficeShow officeShow = new OfficeShow(userId, username, avatarName, fileDataInfo.getOssId(), id, fileDataInfo.getModuleType(), type);
        String savePath = officeShow.getUrlInfo();
        if (info.getInfo() != null) {
            savePath = savePath + "&info=" + info.getInfo();
        }
        return R.ok(savePath);
    }

    /**
     * 在线编辑保存 （onlyOffice）
     *
     * @param request
     * @param response
     * @return void
     * @Date 2024/12/13 11:25
     **/
    @RequestMapping(path = "/callback/onlyOffice", method = {RequestMethod.POST, RequestMethod.GET})
    public void callBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
        FilesEditingDto filesEditingDto = new FilesEditingDto(request);
        String type = filesEditingDto.getType();
        unificationFile.gssUploadService(type);

        PrintWriter writer = response.getWriter();
        Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\\A");
        String body = scanner.hasNext() ? scanner.next() : "";

        JSONObject jsonObj = JSONObject.parseObject(body);
        Long status = jsonObj.getLong("status");
        //* 0 - 找不到带有密钥标识符的文档，
        //* 1 - 正在编辑文档，
        //* 2 - 文件已准备好保存， //自动保存，生成历史版本
        //* 3 - 发生了文档保存错误，
        //* 4 - 文件关闭，没有变化，
        //* 6 - 正在编辑文档，但保存当前文档状态， //手动保存，不生成历史版本
        //* 7 - 强制保存文档时发生错误。
        if (status == 2 || status == 3 || status == 6) {
//        if (  == 2) {
            try {
                RemoteFile remoteFile = unificationFile.getFileDataInfo(filesEditingDto.getTreeId(), filesEditingDto.getUserId(), filesEditingDto.getInfo(),
                    OssModuleOperate.Edit_Save,type);
//                 data = null;
                if (ObjectUtils.isNotEmpty(remoteFile)) {  //获取文件的新名称
                    String realName = remoteFile.getOriginalName(); //获取文件名
                    String suffix = remoteFile.getFileSuffix();
                    filesEditingDto.setName(realName);
                    filesEditingDto.setSuffix(suffix);
                } else {
                    throw new ServiceException("文件不存在");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            String downloadUri = jsonObj.getString("url");
            try {
                URL url = new URL(downloadUri);
                java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
                InputStream stream = connection.getInputStream();

                SysOssVo ossVo = uploadFileService.editSave(stream, filesEditingDto, EditorEnums.onlyOffice);  //去保存数据
                if (ObjectUtils.isEmpty(ossVo)) {
                    return;
                }
                //去保存到个个库中去
                //文件 告知服务进行写入
//                JSONObject uploadInfo = remoteOssUpload.getInfo();
                RemoteFilesBucketPath upload = unificationFile.upload(
                    RemoteFilesUpload.builder()
                        .moduleId(filesEditingDto.getTreeId())
                        .storageId(String.valueOf(ossVo.getOssId()))
                        .versionId(ossVo.getVersionId())
                        .versionName(ossVo.getVersionName())
                        .fileSize(ossVo.getFileSize())
                        .fileSuffix(ossVo.getFileSuffix())
                        .info(filesEditingDto.getInfo()) //模块的参数
                        .type(type)
                        .operate(OssModuleOperate.Edit_Save)
                        .build(),
                    filesEditingDto.getUserId(),
                    type
                );
                connection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
                // 处理异常
            }
        }
        writer.write("{\"error\":0}");
    }





}
